<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\service\DataExportService;
use support\Request;
use support\Log;

/**
 * 数据导出控制器
 */
class DataExportController extends BaseController
{
    protected $exportService;
    
    public function __construct()
    {
        $this->exportService = new DataExportService();
    }
    
    /**
     * 导出应用数据
     */
    public function exportAppData(Request $request)
    {
        try {
            $userId = $request->user->id ?? 0;
            $appId = $request->post('app_id');
            $exportType = $request->post('export_type', 'comprehensive');
            $dateRange = $request->post('date_range', []);
            $format = $request->post('format', 'excel');
            $advancedOptions = $request->post('advanced_options', []);
            $filename = $request->post('filename');
            
            if (empty($appId)) {
                return json(['code' => 400, 'msg' => '应用ID不能为空']);
            }
            
            if (empty($dateRange)) {
                return json(['code' => 400, 'msg' => '时间范围不能为空']);
            }
            
            // 验证用户是否有权限导出该应用的数据
            if (!$this->checkAppPermission($userId, $appId)) {
                return json(['code' => 403, 'msg' => '没有权限导出该应用的数据']);
            }
            
            // 准备导出参数
            $exportParams = [
                'app_id' => $appId,
                'export_type' => $exportType,
                'date_range' => $dateRange,
                'format' => $format,
                'advanced_options' => $advancedOptions,
                'filename' => $filename,
                'user_id' => $userId
            ];
            
            Log::info('Starting data export', $exportParams);
            
            // 执行数据导出
            $result = $this->exportService->exportAppData($exportParams);
            
            if ($result['success']) {
                Log::info('Data export completed successfully', ['file_path' => $result['file_path']]);
                return json([
                    'code' => 200, 
                    'msg' => '数据导出成功',
                    'data' => [
                        'download_url' => $result['download_url'],
                        'file_path' => $result['file_path'],
                        'file_size' => $result['file_size'],
                        'record_count' => $result['record_count']
                    ]
                ]);
            } else {
                throw new \Exception($result['message'] ?? '数据导出失败');
            }
            
        } catch (\Exception $e) {
            Log::error('Data export failed', ['error' => $e->getMessage()]);
            return json(['code' => 500, 'msg' => '数据导出失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取导出历史记录
     */
    public function getExportHistory(Request $request)
    {
        try {
            $userId = $request->user->id ?? 0;
            $page = $request->get('page', 1);
            $limit = $request->get('limit', 20);
            
            $history = $this->exportService->getExportHistory($userId, $page, $limit);
            
            return json([
                'code' => 200,
                'msg' => '获取导出历史成功',
                'data' => $history
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to get export history', ['error' => $e->getMessage()]);
            return json(['code' => 500, 'msg' => '获取导出历史失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除导出文件
     */
    public function deleteExportFile(Request $request)
    {
        try {
            $userId = $request->user->id ?? 0;
            $fileId = $request->post('file_id');
            
            if (empty($fileId)) {
                return json(['code' => 400, 'msg' => '文件ID不能为空']);
            }
            
            $result = $this->exportService->deleteExportFile($userId, $fileId);
            
            if ($result['success']) {
                return json(['code' => 200, 'msg' => '文件删除成功']);
            } else {
                throw new \Exception($result['message'] ?? '文件删除失败');
            }
            
        } catch (\Exception $e) {
            Log::error('Failed to delete export file', ['error' => $e->getMessage()]);
            return json(['code' => 500, 'msg' => '文件删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 验证用户对应用的权限
     */
    private function checkAppPermission($userId, $appId)
    {
        // 这里应该查询数据库验证用户是否拥有该应用
        // 简化实现，实际项目中需要更严格的权限验证
        $app = \think\facade\Db::table('gf_apps')
            ->where('id', $appId)
            ->where('user_id', $userId)
            ->where('is_del', 0)
            ->first();
            
        return !empty($app);
    }
}